package com.ffox.fastDfsUtil;

import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Component
public class FastDfsUtil {
    //    增加文件
    @Value("${fastdfs.nginx.address}")
    public String nginxAddress;

    
//    增加
    public String upload_file(byte[] bs,String extName){
        String path = "";
        try {
            ClientGlobal.init("fastdfs.properties");
            TrackerClient client=new TrackerClient();
            TrackerServer trackerServer=client.getConnection();
            StorageClient storageClient=new StorageClient(trackerServer,null);
            String[] uploadFile=storageClient.upload_file(bs,extName,null);
            storageClient=null;
            trackerServer.close();
            client=null;
            path = this.nginxAddress+"/"+uploadFile[0]+"/"+uploadFile[1];
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return path;
    }


    //    删除文件
    public int delete_file(String group,String name){
        int num = 0;
//            查询图片信息判断是否为空
        if (select_file(group,name) != null){
//                不为空则执行删除
            try {
                ClientGlobal.init("fastdfs.properties");
                TrackerClient client=new TrackerClient();
                TrackerServer trackerServer=client.getConnection();
                StorageClient storageClient=new StorageClient(trackerServer,null);
                num = storageClient.delete_file(group,name);
                storageClient=null;
                trackerServer.close();
                client=null;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (MyException e) {
                e.printStackTrace();
            }
        }
        return num;
    }

    //    查询文件信息
    public FileInfo select_file(String group, String name){
        FileInfo fileInfo = null;
        try {
            ClientGlobal.init("fastdfs.properties");
            TrackerClient client=new TrackerClient();
            TrackerServer trackerServer=client.getConnection();
            StorageClient storageClient=new StorageClient(trackerServer,null);
            fileInfo = storageClient.query_file_info(group, name);
            storageClient=null;
            trackerServer.close();
            client=null;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return fileInfo;
    }
}